package cn.rengy.tool.image;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;   
public class ImageUtils {  
	private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    public enum ImageType {
        jpg,
        JPG,
        tiff,
        TIFF,
        bmp,
        BMP,
        gif,
        GIF,
        png,
        PNG,
        jpeg,
        JPEG,
        tif,
        TIF,
        wbmp,
        WBMP
    }
	private static boolean checkColor(Color c,int scope){
        int red = c.getRed();
        int blue = c.getBlue();
        int green = c.getGreen();
        if(red < scope && blue < scope && green < scope){
            return true;
        }
        return false;//画出来
    }
    private static boolean checkRedColor(Color c,int scope){
        int red = c.getRed();
        int blue = c.getBlue();
        int green = c.getGreen();
        if(red >(255-scope) && blue < scope && green < scope){
            return true;
        }
        return false;//画出来
    }
    //scope 最优值150
    public static void extractSeal(File oldFile,File newFile, int scope) throws IOException {
    	extractColor("red", oldFile, newFile,  scope);
    }
    //scope 最优值150
    public static void extractWord(File oldFile,File newFile, int scope) throws IOException {
    	extractColor("black", oldFile, newFile,  scope);
    }
    
    public static void extractColor(String type,File oldFile,File newFile, int scope) throws IOException {
    	BufferedImage image = ImageIO.read(oldFile);
        int width = image.getWidth();
        int height = image.getHeight();
        
        BufferedImage image2 = new BufferedImage(width, height,     BufferedImage.TYPE_INT_RGB);
     // 获取Graphics2D
     Graphics2D g2d = image2.createGraphics();

     // ----------  增加下面的代码使得背景透明  -----------------
     image2 = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
     g2d.dispose();
     g2d = image2.createGraphics();
     // ----------  背景透明代码结束  -----------------


     g2d.setStroke(new BasicStroke(1));
     //释放对象
     
        for(int row = 0; row < width; row++){
            for(int col = 0; col < height; col++){
                int rgb = image.getRGB(row, col);
                Color c = new Color(rgb);
                boolean b=false;
                if(type.equals("black")) {
                	b=checkColor(c,scope);
                }else if(type.equals("red")) {
                	b=checkRedColor(c,scope);
                }
                if(b){
                 // 画图
                    g2d.setColor(c);
                    g2d.drawLine(row, col, row, col);
                }
            }
        }
        g2d.dispose();
		ImageIO.write(image2, "png", newFile);
    }
    /**
     * 按高等比例缩放
     * @param oldFile
     * @param newFile
     * @param height
     * @throws IOException
     */
    public static void zipByHeight(File oldFile,File newFile, int height) throws IOException {
    	BufferedImage image=ImageIO.read(oldFile);
    	//int srcWidth=image.getWidth();
       // int srcHeight=image.getHeight();
        //int width = (int) ((double)height/srcHeight*srcWidth);
        //.keepAspectRatio(false)//保持图片的长宽比例，默认为true，如果设置成false。强行输出的话，会造成图片可能会变形。
        Thumbnails.of(image).height(height).toFile(newFile);
    }
    /**
     * 按宽等比例缩放
     * @param oldFile
     * @param newFile
     * @param width
     * @throws IOException
     */
    public static void zipByWidth(File oldFile,File newFile, int width) throws IOException {
    	BufferedImage image=ImageIO.read(oldFile);
    	//int srcWidth=image.getWidth();
        //int srcHeight=image.getHeight();
        //int height = (int)((double)width/srcWidth*srcHeight);
        //.keepAspectRatio(false)//保持图片的长宽比例，默认为true，如果设置成false。强行输出的话，会造成图片可能会变形。
        Thumbnails.of(image).width(width).toFile(newFile);
    }
//    public static void zipRatio(File oldFile,File newFile, int width, int height) throws IOException {  
//        BufferedImage image=ImageIO.read(oldFile);
//        if(width<0) {
//        	width=image.getWidth();
//        }
//        if(height<0) {
//        	height=image.getHeight();
//        }
//        Thumbnails.of(image).size(width, height).toFile(newFile);
//    }
    /**
     * 固定尺寸调整图片
     * @param oldFile
     * @param newFile
     * @param width
     * @param height
     * @throws IOException
     */
    public static void zipFixedSize(File oldFile,File newFile, int width, int height) throws IOException {  
        BufferedImage image=ImageIO.read(oldFile); //相机拍摄的图片会失真 有一层红色
        if(width<0) {
        	width=image.getWidth();
        }
        if(height<0) {
        	height=image.getHeight();
        }
        Thumbnails.of(image).size(width, height)
                .keepAspectRatio(false)//保持图片的长宽比例，默认为true，如果设置成false。强行输出的话，会造成图片可能会变形。
                .toFile(newFile);
    }
    /**
     * 原尺寸原质量压缩压缩
     * @param oldFile
     * @param newFile
     * @throws IOException
     */
    public static void zipScale1(File oldFile,File newFile) throws IOException {
        BufferedImage image=ImageIO.read(oldFile); //相机拍摄的图片会失真 有一层红色

        Thumbnails.of(image).scale(1).outputFormat("jpg").outputQuality(1).toFile(newFile);
    }

    public static void zipScaleByQuality(double quality,File oldFile,File newFile) throws IOException {
        BufferedImage image=ImageIO.read(oldFile); //相机拍摄的图片会失真 有一层红色

        Thumbnails.of(image)
                .scale(1)//按照比例进行缩放
                .outputFormat("jpg").outputQuality(quality).toFile(newFile);
    }
    
    
    public static void format(ImageType format,File oldFile,File newFile) throws IOException {
        BufferedImage image=ImageIO.read(oldFile); //相机拍摄的图片会失真 有一层红色
        
        Thumbnails.of(image).scale(1).outputFormat(format.name()).toFile(newFile);
    }
    /**
     * 给图片添加水印
     * @param sourceFile
     * @param newFile
     * @param watermarkImage
     * @throws IOException
     */
    public static void watermark(File sourceFile,File newFile,File watermarkImage) throws IOException {
    	BufferedImage image=ImageIO.read(sourceFile);//相机拍摄的图片会失真 有一层红色
        //int width=image.getWidth();
        //int height=image.getHeight();
    	BufferedImage shuiyin=ImageIO.read(watermarkImage);
    	Thumbnails.of(image).scale(1).watermark(Positions.BOTTOM_RIGHT, shuiyin, 0.8f).toFile(newFile);
    	
    }

    /**
     * 生成图片
     * @param text
     */
    public static void createImage( String text){

        //从原图中找出300x300的大小来显示水印文本

        BufferedImage bi = new BufferedImage(300, 300 ,BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bi.createGraphics();

        int fontSize=16;
        Font font=new Font("Courier", Font.PLAIN, fontSize);
        int textWidth = g.getFontMetrics(font).stringWidth(text);
        //设置绘图区域透明

        bi = g.getDeviceConfiguration().createCompatibleImage(textWidth+5, fontSize+5,Transparency.TRANSLUCENT);

        //字体、字体大小，透明度，旋转角度

        g = bi.createGraphics();
        
        g.setFont(font);
        
        //g.rotate(rotate);

        g.setColor(Color.WHITE);

        //设置文本显示坐标，以上述中的300x300位置为0,0点

        g.drawString(text, 0,  fontSize);
        g.dispose();
        try {
			Thumbnails.of(bi).size(textWidth+5, fontSize+5).toFile("D:/sy-white.png");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public static void main(String args[]) throws IOException {
    	String s[]=ImageIO.getWriterFormatNames();
    	for(int i=0;i<s.length;i++) {
    		System.out.println(s[i]);
    	}
    	
    	//createImage("中云科智（北京）科技有限公司拟 提供技术支持@版权");
    	File sourceFile=new File("D:/tmp/11.png");
    	File newFile=new File("D:/tmp/13.jpg");
    	//watermark( sourceFile, sourceFile,new File("D:/watermark-white.png"));
        zipScaleByQuality(0.5, sourceFile, newFile);
//    	File oldFile=new File("C:/image/ps.jpg");
//    	File newFile=new File("C:/image/ps-new.jpg");
//    	//BufferedImage image=toBufferedImage(oldFile.getAbsolutePath());
//    	BufferedImage image=ImageIO.read(oldFile);
//    	int srcWidth=image.getWidth();
//        int srcHeight=image.getHeight();
//        System.out.println("原图尺寸："+srcWidth+"*"+srcHeight);
//        zipByHeight(oldFile, newFile, 200);
    }
    
   
    /*private static BufferedImage toBufferedImage(String file) {
		使用twelvemonkeys之前对相机图片失真的解决方案
    	Image image = Toolkit.getDefaultToolkit().getImage(file);
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}
		// This code ensures that all the pixels in the image are loaded
		image = new ImageIcon(image).getImage();
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			int transparency = Transparency.OPAQUE;
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}
		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
		}
		// Copy image to buffered image
		Graphics g = bimage.createGraphics();
		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return bimage;
	}*/
}

